/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs;

import org.digitalsoul.switchplugin.patterns.IPattern;
import org.digitalsoul.switchplugin.patterns.NamedCompoundPattern;
import org.digitalsoul.switchplugin.patterns.PatternType;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import java.util.Collection;


public class PreferencesPage extends PreferencePage implements IWorkbenchPreferencePage {

    private PatternConfigurator config;

    private Composite mainPanel;

    private List addedSubPatternList;

    private Combo patternsCombo;

    private Label subPatternHelpLabel;

    @Override
    protected Control createContents(Composite parent) {
        mainPanel = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout(1, false);
        mainPanel.setLayout(layout);
        Label label = new Label(mainPanel, SWT.NONE);
        label.setText("Active Configuration");
        
        patternsCombo = new Combo(mainPanel, SWT.READ_ONLY);
        addPatternsComboItems();
        patternsCombo.addSelectionListener(new SelectionAdapter() {
            
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                int selectionIndex = patternsCombo.getSelectionIndex();
                config.selectCurrentPattern(patternsCombo.getItem(selectionIndex));
                updateConfigSummary();
            }
        });

        addHelpLabel("add multiple sub-patterns to a pattern configuration to match a certain file");
        
        label = new Label(mainPanel, SWT.NONE);
        label.setText("");

        label = new Label(mainPanel, SWT.NONE);
        label.setText("Sub-Patterns");

        addConfigSummary();

        label = new Label(mainPanel, SWT.NONE);
        label.setText("");

        label = new Label(mainPanel, SWT.NONE);
        label.setText("Add Pattern");

        final Combo subPatternsCombo = new Combo(mainPanel, SWT.READ_ONLY);
        subPatternsCombo.add(PatternType.FILE_LOCATION.toString());
        subPatternsCombo.add(PatternType.FILENAME_EXTENSION.toString());
        subPatternsCombo.add(PatternType.FILENAME_SUFFIX.toString());
        subPatternsCombo.select(0);
        subPatternsCombo.addListener(SWT.Selection, new Listener() {

            public void handleEvent(Event arg0) {
                subPatternHelpLabel.setText(getHelpText(subPatternsCombo.getItem(subPatternsCombo.getSelectionIndex())));
                subPatternHelpLabel.update();
            }
        });
        
        subPatternHelpLabel = addHelpLabel(getHelpText(PatternType.FILE_LOCATION.toString()));

        final Composite patternPanel = new Composite(mainPanel, SWT.NONE);
        patternPanel.setLayout(new GridLayout(2, false));

        final Text textField = new Text(patternPanel, SWT.BORDER);
        GridData data2 = new GridData();
        data2.minimumWidth = 250;
        data2.grabExcessHorizontalSpace = true;
        textField.setLayoutData(data2);

        Button addButton = new Button(patternPanel, SWT.BORDER);
        addButton.setText("Add");
        addButton.addListener(SWT.Selection, new Listener() {

            public void handleEvent(Event event) {
                String selectedValue = subPatternsCombo.getItem(subPatternsCombo.getSelectionIndex());
                config.addSubPattern(selectedValue, textField.getText());
                textField.setText("");
                updateConfigSummary();
            }
        });
        label = new Label(mainPanel, SWT.NONE);
        label.setText("");
        return parent;
    }

    private String getHelpText(String type) {
        String helpText = "";
        if (type.equals(PatternType.FILE_LOCATION.toString())) {
            helpText = "e.g  src/main  to match: src/main/**/file.txt";
        }
        else if (type.equals(PatternType.FILENAME_EXTENSION.toString())) {
            helpText = "e.g  java  to match: 'Main.java'";
        }
        else if (type.equals(PatternType.FILENAME_SUFFIX.toString())) {
            helpText = "e.g  TestCase  to match 'MyTestCase.java'";
        }
        return helpText;
    }

    private Label addHelpLabel(String helpText) {
        Label helpLabel = new Label(mainPanel, SWT.WRAP);
        helpLabel.setText(helpText);
        Font font = helpLabel.getFont();
        font.size-=2;
        helpLabel.setFont(font);
        helpLabel.setForeground(mainPanel.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
        return helpLabel;
    }

    private void addPatternsComboItems() {
        for (NamedCompoundPattern pat : config.getPatterns()) {
            patternsCombo.add(pat.getName());
        }
        patternsCombo.select(0);
    }

    private void addConfigSummary() {
        addedSubPatternList = new List(mainPanel, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
        GridData data = new GridData(GridData.FILL_BOTH);
        data.minimumHeight = 100;
        addedSubPatternList.setLayoutData(data);
        addPatternLabelsToList();
        Button button = new Button(mainPanel, SWT.PUSH);
        button.setText("Remove");
        button.addListener(SWT.Selection, new Listener() {

            public void handleEvent(Event arg0) {
                
                for (String patternName : addedSubPatternList.getSelection()) {
                    config.removeSubPattern(patternName);
                }
                updateConfigSummary();
            }
        });
    }

    private void addPatternLabelsToList() {
        for (final IPattern pattern : config.getSubPatterns()) {
            addedSubPatternList.add(pattern.toString());
        }
    }

    protected void updateConfigSummary() {
        addedSubPatternList.removeAll();
        addPatternLabelsToList();
        addedSubPatternList.update();
    }
    
    protected void updatePatternCombo() {
        patternsCombo.removeAll();
        addPatternsComboItems();
        patternsCombo.update();
    }
    
    @Override
    public boolean performOk() {
        save();
        return true;
    }
        
    @Override
    protected void performDefaults() {
        initializeConfigurator(Preferences.getDefaults());
        addedSubPatternList.removeAll();
    }
    
    @Override
    protected void performApply() {
        save();
    }

    private void save() {
        Preferences.savePatterns(config.getPatterns());
    }

    public void init(IWorkbench workbench) {
        initializeConfigurator(Preferences.loadPatterns());
    }

    private void initializeConfigurator(Collection<NamedCompoundPattern> patterns) {
        config = new PatternConfigurator(patterns);
        if (patterns.size() > 0) {
            config.selectCurrentPattern(patterns.iterator().next().getName());            
        }        
    }
}
